<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>库存管理</el-breadcrumb-item>
      <el-breadcrumb-item>出库管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--左上功能区-->
    <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd">新增
    </el-button>
<!--    <el-upload action="http://localhost:10060/stock/out/upload" style="margin: 0 10px;display: inline-block" :show-file-list="false" :on-success="successUpload">-->
<!--      <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini">导入-->
<!--      </el-button></el-upload>-->
    <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"
        :disabled="multiple">导出
    </el-button>
    <el-popconfirm title="确定删除这些数据吗?" @confirm="selectAndDelete" icon-color="red">
      <el-button
          slot="reference"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          style="margin-left: 10px">批量删除
      </el-button>
    </el-popconfirm>
    <!--  查询表单-->
    <el-divider></el-divider>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="85px" >
      <el-form-item label="类别名称" prop="categoryName">
        <el-input
            v-model="queryParams.categoryName"
            placeholder="请输入类别名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="库存名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输库存名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="出库时间">
        <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <!--主体显示列表-->
    <el-table
        :data="tableData"
        @selection-change="handleSelection"
        style="width: 100%">
      <el-table-column
          fixed
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
          prop="categoryName"
          label="类别名称">
      </el-table-column>
      <el-table-column
          prop="name"
          label="库存名称">
      </el-table-column>
      <el-table-column
          prop="number"
          sortable
          label="数量">
      </el-table-column>
      <el-table-column
          prop="unit"
          label="规格(单位)">
      </el-table-column>
      <el-table-column
          prop="stockOutDate"
          label="出库日期"
          width="180"
          sortable>
      </el-table-column>
      <el-table-column
          prop="notes"
          label="备注"
          width="300"
          header-align="center">
      </el-table-column>
      <el-table-column
          label="操作"
          fixed="right"
          width="150"
          header-align="center">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="text" size="mini" icon="el-icon-edit">编辑
          </el-button>
          <el-button @click="openDeleteConfirm(scope.row)" type="text" icon="el-icon-delete" size="mini"> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <!--页码组件-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 50, 100, 500,1000,5000]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <!--    新增表单-->
      <el-dialog title="新增" :visible.sync="dialogVisible" width="435px" :before-close="handleClose">
        <el-form :model="form" ref="addForm" :rules="rules" label-width="120px">
          <el-form-item label="类别名称" prop="categoryName">
            <el-select v-model="form.categoryName" placeholder="请选择类别名称">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存名称" prop="name">
            <el-input v-model="form.name" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="form.number" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="规格（单位）" prop="unit">
            <el-input v-model="form.unit" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.notes" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="出库日期" prop="stockOutDate">
            <el-date-picker
                v-model="form.stockOutDate"
                type="date"
                placeholder="选择出库日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="insertNew('addForm')">确 定</el-button>
  </span>
      </el-dialog>
      <!--    编辑表单-->
      <el-dialog title="编辑" :visible.sync="updatedialogVisible" width="435px" :before-close="handleClose">
        <el-form :model="updateform" ref="updateForm" :rules="rules" label-width="120px">
          <el-form-item label="类别名称" prop="categoryName">
            <el-select v-model="updateform.categoryName" placeholder="请选择类别名称">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存名称" prop="name">
            <el-input v-model="updateform.name" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="updateform.number" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="规格（单位）" prop="unit">
            <el-input v-model="updateform.unit" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="updateform.notes" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="出库日期" prop="stockOutDate">
            <el-date-picker
                v-model="updateform.stockOutDate"
                type="date"
                placeholder="选择出库日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="updatedialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="update('updateForm')">确 定</el-button>
  </span>
      </el-dialog>
      <!-- 预览弹窗表格 -->
      <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
        <el-table :data="selectData" id="selectTable" height="380px">
          <el-table-column
              type="index"
              width="50">
          </el-table-column>
          <el-table-column
              prop="categoryName"
              :show-overflow-tooltip="true"
              label="类别名称">
          </el-table-column>
          <el-table-column
              prop="name"
              :show-overflow-tooltip="true"
              label="库存名称">
          </el-table-column>
          <el-table-column
              prop="number"
              :show-overflow-tooltip="true"
              label="数量">
          </el-table-column>
          <el-table-column
              prop="unit"
              :show-overflow-tooltip="true"
              label="规格(单位)">
          </el-table-column>
          <el-table-column
              prop="stockOutDate"
              :show-overflow-tooltip="true"
              label="出库日期"
              width="180"
              sortable>
          </el-table-column>
          <el-table-column
              prop="notes"
              :show-overflow-tooltip="true"
              label="备注"
              header-align="center">
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footter">
          <el-button type="primary" @click="exportExcel">确定导出</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import BaseUrl from "@/http/BaseUrl";
import TokenAxios from "@/http/TokenAxios";
import axios from "axios";
import XLSX from "xlsx";
import FileSaver from "file-saver";

export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        categoryName: undefined,
        start: undefined,
        end: undefined,
      },
      // 日期范围
      dateRange: [],
      //导入导出显示参数
      multiple: true,
      //新增表单显示参数
      dialogVisible: false,
      // 修改表单显示参数
      updatedialogVisible: false,
      search: '',
      currentPage: 1,
      tableData: [],
      selectData:[],
      selectWindow: false,
      // 新增表单
      form: {},
      //修改表单
      updateform: {},
      //类别下拉框的数据
      options: [],
      //多选数组
      ids: [],
      //总页码
      total: 1,
      rules: {
        categoryName: [{required: true, message: '请选择库存类别', trigger: 'change'}],
        name: {required: true, message: '请输入库存名称', trigger: 'blur'},
        number: {required: true, message: '请输入出库数量', trigger: 'blur'},
        unit: {required: true, message: '请输入出库物料规格(单位)', trigger: 'blur'},
        stockOutDate: {required: true, message: '请选择出库日期', trigger: 'change'}
      }
    }
  },
  methods: {
    //批量删除
    selectAndDelete() {
      let url = BaseUrl.SOTCK + '/stock/out/batch/delete';
      console.log('url = ' + url);
      axios.create({
        'headers': {
          'Authorization': JSON.parse(localStorage.getItem('loginInfo')).token
        }
      }).post(url, this.ids).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.$message({
            message: '数据已成功删除',
            type: 'success'
          });
          this.getList();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    //提交表单的时候点到空白处的事件
    handleClose(done) {
      this.$confirm('当前出库单未提交,确认关闭吗？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    //导入按钮成功实践
    successUpload(res){
      if (res.state=== 0){
        this.$message.success("批量导入成功")
        this.getList()
      }else {
        this.$message.error(res.message)
      }
    },
    // 处理预览弹窗格式化数据
    getExcel(dom, title = '默认标题'){
      var excelTitle = title;
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      // 获取二进制字符串作为输出
      var wbout = XLSX.write(wb,{bookType:"xlsx",bookSST:true,type:"array"});
      try {
        FileSaver.saveAs(
            new Blob([wbout],{type:"application/octet-stream"}),
            excelTitle + ".xlsx"
        );
      }catch (e){
        if (typeof console !== "undefined") console.log(e,wbout);
      }
      return wbout;
    },
    // 点击确定导出
    exportExcel(){
      this.getExcel('#selectTable', '出库数据表');
    },
    // 点击导出按钮显示预览弹窗
    exportExcelSelect(){
      if (this.selectData.length < 1){
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      this.selectWindow=true
    },
    //导出按钮点击事件
    handleExport() {
      if (this.selectData.length < 1){
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      this.selectWindow=true
    },
    //多选框监听事件
    handleSelection(row) {
      this.ids = row
      this.selectData = row;
      //如果没选择任何行就禁用导入导出按钮
      this.multiple = this.ids.length === 0;
    },
    //加载表单中的类别下拉框
    loadCategory() {
      let url = BaseUrl.SOTCK + '/stock/category/list';
      console.log('url = ' + url);
      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.options = jsonResult.data;
          console.log(this.options)
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //新增按钮点击事件
    handleAdd() {
      this.dialogVisible = true
      this.form = {}
      this.loadCategory();
    },
    //搜索按钮点击事件
    handleQuery() {
      this.queryParams.start = this.dateRange[0]
      this.queryParams.end = this.dateRange[1]
      let url = BaseUrl.SOTCK + '/stock/out/search';
      console.log('url = ' + url);
      console.log(this.queryParams.pageNum)
      TokenAxios.post(url, this.queryParams).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //重置按钮点击事件
    resetQuery(formName) {
      this.dateRange = [];
      this.$refs[formName].resetFields();
      this.queryParams.pageSize = 10;
      this.queryParams.pageNum = 1;
      console.log(this.queryParams)
      this.getList()
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //新增数据
    insertNew(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          let url = BaseUrl.SOTCK + '/stock/out/insert'
          console.log('url = ' + url);
          TokenAxios.post(url, this.form).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.$message({
                message: '新增出库单成功！',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    //编辑按钮
    handleEdit(row) {
      this.loadCategory();
      let url = BaseUrl.SOTCK + '/stock/out/' + row.id;
      console.log('url = ' + url)
      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000){
          this.updateform = jsonResult.data;
          console.log(this.updateform)
        }else {
          let title = '操作失败';
          this.$alert(message, title,{
            confirmButtonText: '确定',
            callback:action => {}
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = "执行程序过程中出现错误，请打开浏览器的控制台查看详细错误信息!";
        this.$alert(message,title,{
          confirmButtonText:'确定',
          callback:action => {}
        });
        console.log(error)
      })
      this.updatedialogVisible = true;
    },
    // 编辑后的确认按钮
    update(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updatedialogVisible = false
          let url = BaseUrl.SOTCK + '/stock/out/update'
          console.log('url = ' + url);
          TokenAxios.post(url, this.updateform).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 20000) {
              this.$message({
                message: '修改出库订单成功！',
                type: 'success'
              });
              this.resetForm(formName);
              this.getList()
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击删除提示
    openDeleteConfirm(row) {
      let message = '此操作将永久删除该数据，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(row);
      }).catch(() => {
      });
    },
    handleDelete(row) {
      let url = BaseUrl.SOTCK + '/stock/out/' + row.id + '/delete';
      console.log('url = ' + url);

      TokenAxios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除该数据成功！',
            type: 'success'
          });
          this.getList();
        } else if (jsonResult.state == 50100) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.getList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    //切换每页最大显示
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      if (this.queryParams.name === undefined && this.queryParams.categoryName === undefined && this.dateRange.length === 0) {
        this.getList()
      } else {
        this.handleQuery()
      }
    },
    // 翻页方法
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      if (this.queryParams.name === undefined && this.queryParams.categoryName === undefined && this.dateRange.length === 0) {
        this.getList()
      } else {
        this.handleQuery()
      }
    },
    //获取列表数据的请求
    getList() {
      let page = this.queryParams.pageNum;
      let size = this.queryParams.pageSize;
      console.log('page = ' + page);
      console.log('size = ' + size);
      let url = BaseUrl.SOTCK + '/stock/out/list?page=' + page + '&size=' + size;
      console.log('url = ' + url);
      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    loadIndex() {
      this.getList()
    }
  },
  mounted() {
    this.loadIndex()
  }

}
</script>
